#include <ESP8266WiFi.h>
#include <WiFiManager.h> // 自动配网
#include <PubSubClient.h>
#include <ArduinoJson.h>

// MQTT服务器地址和端口
const char *mqtt_server = "106.14.209.20";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup()
{
  Serial.begin(115200);

  // 每次启动都清除上一次 WiFi 配置，进入热点配网
  WiFiManager wifiManager;
  wifiManager.resetSettings();               // 强制清除配置
  wifiManager.autoConnect("ESP8266-Config"); // 创建热点，进入网页配置

  Serial.println("WiFi connected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // 设置 MQTT 服务器
  client.setServer(mqtt_server, mqtt_port);
}

void reconnect()
{
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP12F_Client"))
    {
      Serial.println("connected");
      client.subscribe("location/sensors/1");
    }
    else
    {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void publishSensorData()
{
  StaticJsonDocument<256> doc;
  doc["id"] = 2;
  doc["indoor"] = true;

  JsonArray sensors = doc.createNestedArray("sensors");

  JsonObject rtk = sensors.createNestedObject();
  rtk["name"] = "RTK";
  JsonObject rtk_data = rtk.createNestedObject("data");
  rtk_data["unit"] = "°";
  JsonArray rtk_value = rtk_data.createNestedArray("value");
  rtk_value.add(121.8971667);
  rtk_value.add(30.90422046);

  JsonObject uwb = sensors.createNestedObject();
  uwb["name"] = "UWB";
  JsonObject uwb_data = uwb.createNestedObject("data");
  uwb_data["unit"] = "cm";
  JsonArray uwb_value = uwb_data.createNestedArray("value");
  uwb_value.add(600);
  uwb_value.add(200);

  char buffer[256];
  size_t n = serializeJson(doc, buffer);
  client.publish("location/sensors/1", buffer, n);
}

void loop()
{
  if (!client.connected())
  {
    reconnect();
  }
  client.loop();
  publishSensorData();
  delay(2000);
}
